package com.future.common.base;

import com.future.common.bean.Result;
import com.future.common.exception.BadRequestException;
import com.future.common.jfinalcustom.MyQrCodeRender;
import com.future.common.utils.ValidationUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;


/**
 * controller的基类，封装一些通用的逻辑
 * 
 * @author Leon.Zhang
 *
 */
public class BaseController extends Controller {
	/**
	 * 返回执行结果
	 * 
	 * @param result
	 */
	protected void renderResult(Object result) {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(result);
		res.setCode("200");
		renderJson(res);
	}

	/**
	 * 执行成功
	 */
	protected void renderSuccess() {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(null);
		res.setCode("200");
		renderJson(res);
	}
	/**
	 * 从request中获取json,校验hibernate validator 注解
	 * @param type
	 * @return
	 */
	protected <T> T getJsonBody(Class<T> type) {
		return getJsonBody(type, true);
	}
	/**
	 * 获取jsonbody
	 * @param type
	 * @param validate
	 * @return
	 */
	protected <T> T getJsonBody(Class<T> type, boolean validate) {
		String jsonStr = HttpKit.readData(getRequest());
		T result = null;
		try{
			result = JsonKit.parse(jsonStr, type);
		}catch (Exception e) {
			throw new BadRequestException("Bad Request");
		}
		if(result !=null && validate){
			ValidationUtil.checkValidation(result);
		}
		return result;
	}
	
	/**
	 * 支持qrcode底部带文字
	 * @param content
	 * @param width
	 * @param height
	 * @param errorCorrectionLevel
	 * @param underWords
	 */
	public void renderQrCode(String content, int width, int height, char errorCorrectionLevel, String upperWords, String underWords) {
		render(new MyQrCodeRender(content, width, height, errorCorrectionLevel,upperWords, underWords));
	}
}
